package com.geh.learn.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by gehui on 2017/3/30.
 */
public class ReadFileTest {
    public static void main(String[] args) {
        String filePath = "/Users/gehui/work/gitproject/jdk-learn/src/main/resources/TestFile.txt";
        try {
            // 一行读出文件的所有内容
            String fileContent = new String(
                    Files.readAllBytes(
                            Paths.get(filePath)
                    )
            );
            System.out.println(fileContent);

            // 逐行读出文件内容
            Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8).forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }

        // try的不同用法，stream的过滤处理
        List<String> list;
        try(Stream<String> stream = Files.lines(Paths.get(filePath))) {
            //1. filter line 3
            //2. convert all content to upper case
            //3. convert it into a List
            list = stream
                    .filter(line -> !line.startsWith("line3"))
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());

            list.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }

        // BufferedReader + Stream
        try(BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) {
            //br returns as stream and convert it into a List
            list = br.lines().collect(Collectors.toList());
            list.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
